package com.my.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.admin.entity.Image;
import com.my.admin.service.ImageService;
import com.my.admin.util.FastDFSUtil;
import com.my.admin.util.FileUploadUtil;
import com.my.admin.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class ImageController {

    @Autowired
    private ImageService service;

    @Value("${fdfs.web-server-url}")
    private String webServerUrl;

    public final static List<String> IMG_FORMAT = new ArrayList<String>(){{
        add("JPG");add("JPEG");add("PNG");add("GIF");
    }};

    @Autowired
    private FastDFSUtil dfsUtil;

    @PostMapping("image/get")
    public Rest images(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, @RequestBody Image image) {
        return Rest.ok().setData("page", service.pageList(new Page<>(pageNo, pageSize), image));
    }

    @PostMapping("images")
    public Rest add(@RequestBody Image image) {
        if(service.save(image)) {
            return Rest.ok("添加成功！");
        }else {
            return Rest.err("添加失败!");
        }
    }

    @PutMapping("images")
    public Rest edit(@RequestBody Image image) {
        if(service.updateById(image)) {
            return Rest.ok("修改成功！");
        }else {
            return Rest.err("修改失败！");
        }
    }

    @DeleteMapping("images")
    public Rest del(@RequestParam long id) {
        Image image = service.getById(id);
        dfsUtil.delete(image.getLink());
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }else {
            return Rest.err("删除失败！");
        }
    }

    @PostMapping("image/imageUpload")
    public Rest imageUpload(@RequestParam("file") MultipartFile file) {
        return FileUploadUtil.verify(file, IMG_FORMAT, webServerUrl, dfsUtil);
    }

    @DeleteMapping("image/delete")
    public Rest delete(@RequestParam(defaultValue = "") String path) {
        if(StrUtil.isNotBlank(path)) {
            dfsUtil.delete(path);
        }
        return Rest.ok("图片清理成功！");
    }

}
